import json
from app import db
from flask import Blueprint, render_template, request, url_for, redirect
bp = Blueprint('BorrowerInformation', __name__, url_prefix='/Borrower')
from app.models import User
from app.models import Book


#Json序列化
import decimal

class DecimalEncoder(json.JSONEncoder):

    def default(self, o):
        if isinstance(o, decimal.Decimal):
            return float(o)
        super(DecimalEncoder, self).default(o)
@bp.route('/Information', methods=['GET', 'POST'])
def borrower():
    print("I am here")
    users= User.query.all()
    context = {
            'inf': users
        }
    return render_template('Borrower Information.html', **context)



@bp.route('/delete', methods=['GET', 'POST'])
def delete():
    bid = request.form['name']
    example = User.query.get(bid)
    print(example)
    db.session.delete(example)
    db.session.commit()
    users = User.query.all()
    print(users)
    userLists = [user.to_dict() for user in users]
    print(userLists)
    return json.dumps(userLists, cls=DecimalEncoder)

@bp.route('/modify', methods=['GET', 'POST'])
def modify():
    username = request.form['id']
    print(username)
    users = User.query.filter_by(username=int(username)).all()
    print(users)
    usersLists = [user.to_dict() for user in users]
    print(usersLists)
    return json.dumps(usersLists,cls=DecimalEncoder)

@bp.route('/modifyResult', methods=['PUT'])
def modifyResult():

    username = request.form['username']
    password = request.form['password']

    user = User(username=username, password=password)
    example = User.query.get(int(username))
    db.session.delete(example)
    db.session.add(user)
    db.session.commit()

    users = User.query.all()
    usersLists = [user.to_dict() for user in users]
    return json.dumps(usersLists,cls=DecimalEncoder)




@bp.route('/search', methods=['GET', 'POST'])
def search():
    data = request.args.get('search')
    example = User.query.filter_by(username=int(data))
    context = {
        'inf': example
        }
    return render_template('Borrower Information.html', **context)


@bp.route('/add', methods=['GET', 'POST'])
def add():
    if request.method == 'GET':
        return render_template('addinf.html')
    else:
        username = request.form['username']
        password = request.form['password']
        user = User(username=username,password=password)
        db.session.add(user)
        db.session.commit()
    return redirect(url_for('BorrowerInformation.borrower'))

@bp.route('/returnUser', methods=['GET', 'POST'])
def returnUser():
    users = User.query.all()
    userLists = [user.to_dict() for user in users]
    return json.dumps(userLists,cls=DecimalEncoder)